// SPDX-License-Identifier: GPL-3.0-or-later

import QtQuick
import QtQuick.Layouts
import Fk
import Fk.Components.LunarLTK
import Fk.Pages.LunarLTK
import Fk.Components.Common

GraphicsBox {
  property string prompt: ""
  property alias generalList: generalList
  property var generals: []
  property var change: []
  property int choiceNum: 0
  property bool convertDisabled: false
  property string rule_type: ""
  property var extra_data
  property bool hegemony: false
  property var choices: []
  property var selectedItem: []
  property bool loaded: false
  property bool changeGeneralBtnVisible: true

  property var friend_cards: []
  property var my_cards: []
  property string friend_recommend
  property string friend_not_determ: ""
  property string friend_selected: ""
  property string my_recommend
  property string selected
  property int changeCount: 0  // 新增属性追踪剩余次数
  property bool changeExhausted: changeCount === 0  // 替代原计算逻辑

  function hideAllChangeButtons() {
      for (var i = 0; i < generalCardList.count; i++) {
          var item = generalCardList.itemAt(i);
          // 查找按钮组件
          if (item && item.children) {
              for (var j = 0; j < item.children.length; j++) {
                  var child = item.children[j];
                  if (child.objectName === "changeGeneralBtn") {
                      child.isClicked = true;  // 标记为已点击，使其消失
                  }
              }
          }
      }
  }

  ListModel {
    id: generalList
  }

  id: root
  title.text: {
    const seatInfo = roomScene.getPhoto(Self.id) && roomScene.getPhoto(Self.id).seatNumber
      ? "你的座次是 " + Lua.tr("seat#" + roomScene.getPhoto(Self.id).seatNumber) + "，"
      : "";
    return seatInfo + "请选择是否出兵占领城池";
  }

  width: generalArea.width + body.anchors.leftMargin + body.anchors.rightMargin
  height: body.implicitHeight + body.anchors.topMargin +
          body.anchors.bottomMargin

  Column {
    id: body
    anchors.fill: parent
    anchors.margins: 40
    anchors.bottomMargin: 20

    Item {
      id: generalArea
      width: (generalList.count > 8 ? Math.ceil(generalList.count / 2)
                                    : Math.max(3, generalList.count)) * 97
      height: generalList.count > 8 ? 290 : 150
      z: 1

      Repeater {
        id: generalMagnetList
        model: generalList.count

        Item {
          width: 93
          height: 130
          x: {
            const count = generalList.count;
            let columns = generalList.count;
            if (columns > 8) {
              columns = Math.ceil(columns / 2);
            }

            let ret = (index % columns) * 98;
            if (count > 8 && index > count / 2 && count % 2 == 1)
              ret += 50;
            return ret;
          }
          y: {
            if (generalList.count <= 8)
              return 0;
            return index < generalList.count / 2 ? 0 : 135;
          }
        }
      }
    }

        Item {
      id: splitLine
      width: parent.width - 80
      height: 6
      anchors.horizontalCenter: parent.horizontalCenter
      clip: true
    }

    Item {
      id: buttonArea
      width: parent.width
      height: 40

      Row {
        //anchors.centerIn: parent
        spacing: 32
        anchors.horizontalCenter: parent.horizontalCenter
        MetroButton {
          id: multiple1Btn
          text: "放弃出兵"

          enabled: canSelect
          onClicked: {
            sendChoiceToServer(1)
          }
        }
        MetroButton {
          id: multiple2Btn
          text: "确认出兵"

          enabled: canSelect
          onClicked: {
            sendChoiceToServer(2)
          }
        }
      }
    }
  }

  Repeater {
    id: generalCardList
    model: generalList

    GeneralCardItem {
      name: model.name
      selectable: true
      draggable: true

      onClicked: {
        if (!selectable) return;
        let toSelect = true;
        for (let i = 0; i < selectedItem.length; i++) {
          if (selectedItem[i] === this) {
            toSelect = false;
            selectedItem.splice(i, 1);
            break;
          }
        }
        if (toSelect && selectedItem.length < choiceNum)
          selectedItem.push(this);
        updatePosition();
      }

      onRightClicked: {
        roomScene.startCheat("GeneralDetail", { generals: [modelData] });
      }

      onReleased: {
        arrangeCards();
      }
      // 替换原有的 MetroButton
      // 替换原有的 changeGeneralBtn 实现
      Rectangle {
          id: changeGeneralBtn
          objectName: "changeGeneralBtn"
          width: 25
          height: 25
          radius: width / 2
          anchors {
              top: parent.top
              right: parent.right
              topMargin: -10
              rightMargin: -10
          }
          opacity:0.75
          
          // 按钮状态控制
          property bool isClicked: false
          visible: !isClicked && root.changeCount > 0  // 绑定到 changeCount
          
          // 按钮颜色
          color: "#88000000"
          border.color: changeArea.containsMouse ? "#f1ca3c" : "#FFFFFF"
          border.width: 2
          
          // 按钮文本
          Text {
              anchors.centerIn: parent
              text: "换"
              color: changeArea.containsMouse ? "#f1ca3c" : "#FFFFFF"
              font.family: fontLibian.name
              font.pixelSize: 18
              font.bold: true
          }
          
          // 鼠标区域
          MouseArea {
              id: changeArea
              anchors.fill: parent
              hoverEnabled: true
              enabled: !isClicked
              
              onClicked: { 
                  console.log("Change button clicked");
                  changeGeneralBtn.isClicked = true;  // 标记为已点击，立即消失
                  
                  if (root.change && root.change.length > 0) {
                      // 执行换将逻辑
                      let newGeneral = root.change.shift();
                      root.changeCount--; // 关键！手动递减次数
                      if (root.generals && model.name) { 
                          let index = root.generals.findIndex(card => card === model.name); 
                          if (index !== -1) {
                              if (root.generalList.get(index)) {
                                  root.generals[index] = newGeneral;
                                  root.generalList.set(index, { "name": newGeneral });
                              }
                          }
                          root.updatePosition();
                      }
                  }  
              }
          }
      }
    }
  }

  function arrangeCards()
  {
    let item, i;

    selectedItem = [];
    for (i = 0; i < generalList.count; i++) {
      item = generalCardList.itemAt(i);
      if (item.y > splitLine.y && item.selectable)
        selectedItem.push(item);
    }

    selectedItem.sort((a, b) => a.x - b.x);

    if (selectedItem.length > choiceNum)
      selectedItem.splice(choiceNum, selectedItem.length - choiceNum);

    updatePosition();
  }

  function updateCompanion(gcard1, gcard2, overwrite) {
    if (Lua.call("IsCompanionWith", gcard1.name, gcard2.name)) {
      gcard1.hasCompanions = true;
    } else if (overwrite) {
      gcard1.hasCompanions = false;
    }
  }

  function updatePosition()
  {
    choices = [];
    let item, magnet, pos, i;
    for (i = 0; i < selectedItem.length && i < resultList.count; i++) {
      item = selectedItem[i];
      choices.push(item.name);
      magnet = resultList.itemAt(i);
      pos = root.mapFromItem(resultArea, magnet.x, magnet.y);
      if (item.origX !== pos.x || item.origY !== item.y) {
        item.origX = pos.x;
        item.origY = pos.y;
        item.goBack(true);
      }
    }
    root.choicesChanged();

    //fightButton.enabled = Lua.call("ChooseGeneralFeasible", root.rule_type, root.choices,
                                //root.generals, root.extra_data);

    for (i = 0; i < generalCardList.count; i++) {
      item = generalCardList.itemAt(i);
      item.selectable = choices.includes(item.name) ||
              Lua.call("ChooseGeneralFilter", root.rule_type, item.name, root.choices,
                    root.generals, root.extra_data);
      if (hegemony) { // 珠联璧合相关
        item.inPosition = 0;
        if (selectedItem[0]) {
          if (selectedItem[1]) {
            if (selectedItem[0] === item) {
              updateCompanion(item, selectedItem[1], true);
            } else if (selectedItem[1] === item) {
              updateCompanion(item, selectedItem[0], true);
            } else {
              item.hasCompanions = false;
            }
          } else {
            if (selectedItem[0] !== item) {
              updateCompanion(item, selectedItem[0], true);
            } else {
              for (let j = 0; j < generalList.count; j++) {
                updateCompanion(item, generalList.get(j), false);
              }
            }
          }
        } else {
          for (let j = 0; j < generalList.count; j++) {
            updateCompanion(item, generalList.get(j), false);
          }
        }
      }
      if (selectedItem.indexOf(item) != -1)
        continue;

      magnet = generalMagnetList.itemAt(i);
      pos = root.mapFromItem(generalMagnetList.parent, magnet.x, magnet.y);
      if (item.origX !== pos.x || item.origY !== item.y) {
        item.origX = pos.x;
        item.origY = pos.y;
        item.goBack(true);
      }
    }

    if (hegemony) { // 主副将调整阴阳鱼
      if (selectedItem[0]) {
        if (selectedItem[0].mainMaxHp < 0) {
          selectedItem[0].inPosition = 1;
        } else if (selectedItem[0].deputyMaxHp < 0) {
          selectedItem[0].inPosition = -1;
        }
        if (selectedItem[1]) {
          if (selectedItem[1].mainMaxHp < 0) {
            selectedItem[1].inPosition = -1;
          } else if (selectedItem[1].deputyMaxHp < 0) {
            selectedItem[1].inPosition = 1;
          }
        }
      }
    }

    for (let i = 0; i < generalList.count; i++) {
      if (Lua.call("GetSameGenerals", generalList.get(i).name).length > 0) {
        convertBtn.enabled = true;
        return;
      }
    }
    convertBtn.enabled = false;
  }
  
  function onMultipleSelected(multiple) {
    root.choices = multiple;
  }

  function sendChoiceToServer(multiple) {
    const generalStr = root.generals.join(',');
    const replyData = multiple + "|" + generalStr;
    
    roomScene.state = "notactive";
    ClientInstance.replyToServer("", replyData);
    close();
  }

    function loadData(data) {
    root.change = data.change;
    root.changeCount = data.change.length; // 初始化次数
    // 添加change数组的变化监听
    //root.changeChanged.connect(function() {
    //    root.changeExhausted = root.change && root.change.length === 0;
    //});

    root.generals = data.cards;
    root.choiceNum = data.num ?? 1;
    root.convertDisabled = !!data.no_c;
    root.hegemony = !!data.heg;
    root.rule_type = data.type; // 若heg为true，默认应用国战选将
    root.extra_data = data.extra;
    for (let i = 0; i < data.cards.length; i++){
      root.generalList.append({ "name": data.cards[i] });
    }
    root.updatePosition();
    // root.refreshPrompt();
  }

  function updateData(data) {
    let [type, value] = data;
    value = value ?? "";
    if (type == "finish") {//结束所有人的选择
      close();
      roomScene.state = "notactive";
      ClientInstance.replyToServer("", root.choices);
    } else if (type == "select") {//增加次数
      currentindex++;
      canSelect=false;
      if(currentindex==index){
        canSelect = true;
      }
      //如果全都选完了，则结束，即currenindex大于3
      if(currentindex > 3){
        close();
        roomScene.state = "notactive";
        ClientInstance.replyToServer("", root.choices);
      }
    }
  }

  function refreshPrompt() {
    prompt = Util.processPrompt(Lua.call("ChooseGeneralPrompt", rule_type, generals, extra_data))
  }
}